import {
  tokenKey
} from '@/config'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth.js'
import {
  fullPath,
  isHttpOrHttps
} from '@/utils/roc'
import {
  login,
  logout,
  logoff
} from '@/mock/login.js'
import {
  getUserProfile
} from '@/mock/user.js'

const state = () => ({
  token: getToken(),
  id: uni.getStorageSync('userInfo').id || 0,
  name: uni.getStorageSync('userInfo').name || '',
  account: uni.getStorageSync('userInfo').account || '',
  avatar: uni.getStorageSync('userInfo').avatar || '',
  permissions: uni.getStorageSync('userInfo').permissions || [],
})
const mutations = {
  /**
   * 设置token
   */
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(state.token)
  },
  /**
   * 清空所有登录状态
   */
  REMOVE_LOGIN_STATE: (state) => {
    state.id = 0
    state.token = ''
    state.account = ''
    state.name = ''
    state.avatar = ''
    state.permissions = []
    removeToken()
    uni.removeStorageSync('userInfo')
  },
  /**
   * 设置用户信息
   */
  SET_USER_INFO: (state, userInfo) => {
    state.id = userInfo.id
    state.account = userInfo.account
    state.name = userInfo.name
    state.avatar = userInfo.avatar
    state.permissions = userInfo.permissions
    uni.setStorageSync('userInfo', userInfo)
  }
}
const actions = {
  /**
   * 登录
   */
  login: ({
    commit
  }, loginForm) => {
    return new Promise((resolve, reject) => {
      login(loginForm).then(res => {
        commit('SET_TOKEN', res.token)
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  },
  /**
   * 获取用户信息
   */
  getInfo({
    commit
  }) {
    return new Promise((resolve, reject) => {
      getUserProfile().then(res => {
        const user = res.user
        const avatar = user.avatar === '' || user.avatar == null || isHttpOrHttps(user.avatar) ?
          user.avatar :
          fullPath(user.avatar)
        const userInfo = {}
        userInfo.id = user.id
        userInfo.account = user.account
        userInfo.name = user.name
        userInfo.avatar = avatar
        userInfo.permissions = res.permissions
        commit('SET_USER_INFO', userInfo)
        resolve(res)
      }).catch((error) => {
        reject(error)
      })
    })
  },
  /**
   * 退出
   */
  logout: ({
    commit
  }) => {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('REMOVE_LOGIN_STATE')
        resolve()
      }).catch(() => {
        reject(error)
      })
    })
  },
  /**
   * 注销
   */
  logoff: ({
    commit
  }) => {
    return new Promise((resolve, reject) => {
      logoff().then(() => {
        commit('REMOVE_LOGIN_STATE')
        resolve()
      }).catch(() => {
        reject(error)
      })
    })
  },
}

export default {
  state,
  mutations,
  actions
}